package com.three.api.protocol;

import com.three.protocol.CommandEnum;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

/**
 * 用户数据报协议包
 *
 * @Author mathua
 * @Date 2017/5/19 15:22
 */
public final class UDPPacket extends Packet {
    private InetSocketAddress address;

    public UDPPacket(short cmd, InetSocketAddress sender) {
        super(cmd);
        this.address = sender;
    }

    public UDPPacket(CommandEnum.Command cmd, int sessionId, InetSocketAddress sender) {
        super(cmd, sessionId);
        this.address = sender;
    }

    public UDPPacket(short cmd) {
        super(cmd);
    }

    public UDPPacket(CommandEnum.Command cmd) {
        super(cmd);
    }

    public UDPPacket(CommandEnum.Command cmd, int sessionId) {
        super(cmd, sessionId);
    }

    @Override
    public InetSocketAddress sender() {
        return address;
    }

    @Override
    public void setRecipient(InetSocketAddress recipient) {
        this.address = recipient;
    }

    @Override
    public Packet response(CommandEnum.Command command) {
        return new UDPPacket(command, sessionId, address);
    }

    @Override
    public Object toFrame(Channel channel) {
        int capacity = HEADER_LEN + getBodyLength();
        ByteBuf out = channel.alloc().buffer(capacity, capacity);
        encodePacket(this, out);
        return new DatagramPacket(out, sender());
    }
}
